//
//  MenuForOrder.m
//  ServiceApp
//
//  Created by User-23 on 12/13/14.
//  Copyright (c) 2014 TrainingCamp. All rights reserved.
//

#import "SubCategoryMenuController.h"
#import "Product.h"
#import "SubCategory.h"
#import "MakeOrderScreen.h"

@interface SubCategoryMenuController ()

@property NSMutableArray *sectionNamesInMenu;
@property NSMutableArray *sectionCategories;

@property SubCategory* selecetedSubCategory;


@end

static NSString *kMenuURL = @"http://78.90.20.186:8080/ProjectRestaurant/menu";
static NSString *kSectionMenu = @"http://78.90.20.186:8080/ProjectRestaurant/menu/subCategories?parentId=";

@implementation SubCategoryMenuController


#pragma mark - View Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // initialize arrays for categories for menu
    self.sectionNamesInMenu = [[NSMutableArray alloc] init];
    self.sectionCategories = [[NSMutableArray alloc] init];
    
    //Listen for categories update events
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(update:)
                                                 name:@"CategoriesLoaded" object:nil];
}

- (void) update:(NSNotification*) note {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData] ;
    });
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self getSubCategories];
}

#pragma mark - Networking

- (void) getSubCategories{
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%ld", kSectionMenu, (long)self.selecetedSubCategoryId]]];

    NSURLSessionDataTask* downloadJSONTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSError* mistake = nil;
        NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&mistake];
        
        if (mistake != nil) {
            NSLog(@"Error : %@", [mistake localizedDescription]);
        }
        else {
            for (NSDictionary *item  in jsonArray) {
                SubCategory *subCat = [[SubCategory alloc] init];
                subCat.name = item[@"name"];
                subCat.categoryId = [item[@"categoryId"] integerValue];
                for (NSDictionary *product in item[@"products"]) {
                    Product * newProduct = [[Product alloc] init];
                    newProduct.name = product[@"name"];
                    newProduct.price = [product[@"price"] floatValue];
                    newProduct.productId = [product[@"productId"] integerValue];
                    [subCat addProduct:newProduct];
                }
                [self.sectionCategories addObject:subCat];
                [self.sectionNamesInMenu addObject:item[@"name"]];
                
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"CategoriesLoaded" object:self userInfo:nil];
            
        }
        
    }];
    [downloadJSONTask resume];
}

#pragma mark - Table View Data Source Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [self.sectionNamesInMenu count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.sectionCategories[section] productsCount];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.sectionNamesInMenu[section];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productCell" forIndexPath:indexPath];
    
    // Configure cell
    cell.textLabel.text = [self.sectionCategories[indexPath.section] productAtIndex:indexPath.row].name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f lv.", [self.sectionCategories[indexPath.section] productAtIndex:indexPath.row].price];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    Product* product = [self.sectionCategories[indexPath.section] productAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"MenuToOrder" sender:product];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    MakeOrderScreen* vc = (MakeOrderScreen*)[segue destinationViewController];
    vc.selectedProduct = sender;
}

@end
